/**
 * 
 */
package edu.university.demo.system.service;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.utils.Clock;

import com.google.common.collect.Lists;
import com.smallchill.core.toolbox.kit.FileKit;

import edu.university.demo.core.constant.Cst;
import edu.university.demo.system.entit.Song;
import edu.university.demo.system.entit.SongInfo;
import edu.university.demo.system.entit.User;
import edu.university.demo.system.repository.SongDao;
import edu.university.demo.system.repository.SongInfoDao;
import edu.university.demo.system.repository.UserDao;

/**
 * 歌曲业务类
 * 
 * @author mayanping
 *
 */
@Service
@Transactional
public class SongService {

	@Autowired
	private SongDao songDao;
	
	@Autowired
	private SongInfoDao songInfoDao;
	
	@Autowired
	private UserDao userDao;
	
	private static Logger logger =  LoggerFactory.getLogger(SongService.class);
	
	private Clock clock = Clock.DEFAULT;
	
	/**
	 * 分页获取歌曲
	 * @param pageNumber 页码
	 * @param pageSize 页显示条数
	 * */
	public Page<Song> getAllSong(int pageNumber, int pageSize) {
		Pageable pageRequest = new PageRequest(pageNumber - 1, pageSize,new Sort(Direction.DESC,"id"));
		return songDao.findAll(pageRequest);
	}
	

	/**
	 * 获取所有歌曲
	 * */
	public List<Song> getAllSong(){
		return Lists.newArrayList(songDao.findAllSongs());
	}
	
	/**
	 * 获取当前用户的歌曲列表
	 * */
	public List<Song> getMySong(String loginName){
		User user = userDao.findByLoginName(loginName);
		
		return Lists.newArrayList(user.getSongList());
	}
	
	/**
	 * 把歌曲和当前用户关联
	 * */
	public void saveSong(Long songId,String loginName){
		User user = userDao.findByLoginName(loginName);
		Song song = songDao.findOne(songId);
		SongInfo songInfo = song.getSongInfo();
		if(user == null || song == null){
			return;
		}
		List<User> userList = Lists.newArrayList(song.getUserList());
		userList.add(user);

		songInfo.setCollectAmout((long)userList.size());
		song.setUserList(userList);
	}
	
	/**
	 * 添加新歌
	 * */
	public boolean newSong(Song song){
		song.setInputTime(clock.getCurrentDate());
		try{
			dealFileName(song);
			
			SongInfo songInfo = new SongInfo();
			song.setSongInfo(songInfo);
			songInfoDao.save(songInfo);
			songDao.save(song);
			return true;
		}catch(Exception e){
			logger.error("创建Song失败",e);
			return false;
		}
	}

	//截取C:\fakepath\****
	private void dealFileName(Song song) {
		
		String fileName = subStr(song.getFileName());
		String imageName = subStr(song.getImageName());
		String lyricName = subStr(song.getLyricName());
		
		song.setFileName(fileName);
		song.setImageName(imageName);
		song.setLyricName(lyricName);
	}


	private String subStr(String fileName) {
		
		return fileName.substring(fileName.lastIndexOf(File.separator) +1);
	}


	public Song getSong(Long id) {
		// TODO Auto-generated method stub
		return songDao.findOne(id);
	}

	public boolean deleteSong(Long id) {
		// TODO Auto-generated method stub
		try{
		songDao.delete(id);
		return true;
		}catch(Exception e){
			logger.error("删除Song失败",e);
			return false;
		}
	}


	public void removeSong(Long songId, String loginName) {
		
		Song updateSong = songDao.findOne(songId);
		SongInfo songInfo = updateSong.getSongInfo();
		
		List<User> userList = updateSong.getUserList();
		User removeUser = null;
		for (User user : userList) {
			
			if(user.getLoginName().equals(loginName)) {
				removeUser = user;
				break;
			}
		}
		if(removeUser != null) {
			userList.remove(removeUser);
		}
		updateSong.setUserList(userList);
		songInfo.setCollectAmout((long)userList.size());
	}


	public void increase(Long id) {
		
		Song song = songDao.findOne(id);
		SongInfo songInfo = song.getSongInfo();
		songInfo.increasePlayTime();
	}


	public String getLyricById(Long id, String lyricPath) throws IOException {
		
		Song song = songDao.findOne(id);
		String fileName = song.getFileName();
		fileName = fileName.substring(0, fileName.lastIndexOf("."));
		fileName = fileName + ".lrc";
		String lyric = 
				FileKit.readUtf8String(Cst.me().getRealPath() +lyricPath + "/" + fileName);
		return lyric;
	}
}
